package com.techshinogongjian.fingerprint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Environment;
import android.util.Log;

public class TesoUtil {
	public static boolean upgradedirPermission(String pkgCodePath) {
		Process process = null;
		DataOutputStream os = null;
		try {
			Log.d("initUsbDevice", "techshino mUsbReceiver1 pkgCodePath = "
					+ pkgCodePath);
			String cmd = "chmod -R 0777 " + pkgCodePath;
			process = Runtime.getRuntime().exec("su"); // 切换到root帐号
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return true;
	}

	public static boolean upgradeRootPermission(String pkgCodePath) {
		Process process = null;
		DataOutputStream os = null;
		try {
			Log.d("initUsbDevice", "techshino mUsbReceiver1 pkgCodePath = "
					+ pkgCodePath);
			String cmd = "chmod 0777 " + pkgCodePath;
			process = Runtime.getRuntime().exec("su"); // 切换到root帐号
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return true;
	}

	public static boolean upgradeown(String pkgCodePath) {
		Process process = null;
		DataOutputStream os = null;
		try {
			Log.d("initUsbDevice", "techshino mUsbReceiver1 pkgCodePath = "
					+ pkgCodePath);
			String cmd = "chown system:system " + pkgCodePath;
			process = Runtime.getRuntime().exec("su"); // 切换到root帐号
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return true;
	}

	public static boolean upgradegroup(String pkgCodePath) {
		Process process = null;
		DataOutputStream os = null;
		try {
			Log.d("initUsbDevice", "techshino mUsbReceiver1 pkgCodePath = "
					+ pkgCodePath);
			String cmd = "chgrp system " + pkgCodePath;
			process = Runtime.getRuntime().exec("su"); // 切换到root帐号
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(cmd + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return true;
	}

	public static void saveBmp(byte[] bitmap) {
		if (bitmap == null)
			return;

		try {
			// 存储文件名
			int i = 0;
			String filename;
			File file;
			while (true) {
				filename = "/sdcard/teso/";
				file = new File(filename);
				if (!file.exists())
					file.mkdir();
				filename = "/sdcard/teso/tesofinger" + i + ".bmp";
				file = new File(filename);

				if (file.exists()) {
					i++;
					continue;

				}

				else {

					break;
				}

			}

			FileOutputStream fileos = new FileOutputStream(filename);

			fileos.write(bitmap);
			fileos.flush();
			fileos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static byte[] readSDFile(String fileName) {
		try {
			File file = new File(Environment.getExternalStorageDirectory(),
					fileName);
			FileInputStream is = new FileInputStream(file);
			byte[] b = new byte[is.available()];
			is.read(b);
			return b;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void saveFile(byte[] any, String name) {

		try {
			// 存储文件名
			int i = 0;
			String filename;
			File file;
			while (true) {
				filename = "/sdcard/teso/";
				file = new File(filename);
				if (!file.exists())
					file.mkdir();
				filename = "/sdcard/teso/" + name + ".txt";
				file = new File(filename);
				if (file.exists()) {
					file.delete();
					continue;
				} else {
					break;
				}
			}
			FileOutputStream fileos = new FileOutputStream(filename);
			fileos.write(any);
			fileos.flush();
			fileos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void savebitmap(byte[] bitmap) {

		try {
			// 存储文件名
			int i = 0;
			String filename;
			File file;
			while (true) {
				filename = "/sdcard/teso/";
				file = new File(filename);
				if (!file.exists())
					file.mkdir();
				filename = "/sdcard/teso/teso" + i + ".bmp";
				file = new File(filename);

				if (file.exists()) {
					i++;
					continue;

				} else {

					break;
				}

			}

			FileOutputStream fileos = new FileOutputStream(filename);

			fileos.write(bitmap);
			fileos.flush();
			fileos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void saveBitmapToPNG(Bitmap bitmap, String bitName)
			throws IOException {
		File file;
		String filename = "/sdcard/teso/";
		file = new File(filename);
		if (!file.exists())
			file.mkdir();
		filename = "/sdcard/teso/" + bitName;
		file = new File(filename);

		if (file.exists()) {
			file.delete();
		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 图片的缩放方法
	 *
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
								   double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	/**
	 * 图片按比例大小压缩方法(根据Bitmap图片压缩)
	 *
	 * @param image
	 * @return
	 */
	public static Bitmap getImage(Bitmap image, int width) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可

		int be = (int) (newOpts.outWidth / width);// be=1表示不缩放
		// if (w > h && w > ww)
		// {// 如果宽度大的话根据宽度固定大小缩放
		// be = (int) (newOpts.outWidth / ww);
		// } else if (w < h && h > hh)
		// {// 如果高度高的话根据宽度固定大小缩放
		// be = (int) (newOpts.outHeight / hh);
		// }
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		if (isBm != null) {
			try {
				isBm.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (image != null && !image.isRecycled()) {
			image.recycle();
			image = null;
		}
		return bitmap;// 压缩好比例大小后再进行质量压缩
	}

	// 改变图像的分辨率，根据图像的宽度等比缩放
	public static Bitmap scaleBitmap(Bitmap bitmap, int width) {
		if (bitmap.getWidth() < width)
			return null;
		try {
			float srcWidth = (float) bitmap.getWidth();
			float srcHeight = (float) bitmap.getHeight();

			float height = width * srcHeight / srcWidth;

			return Bitmap.createScaledBitmap(bitmap, width, (int) height, true);
		} finally {
			if (bitmap != null) {
				bitmap.recycle();
				bitmap = null;
			}
		}
	}

	public static Bitmap getRedTransparentBitmap(Bitmap bmFinger, int width) {
		Bitmap bmFinger1 = scaleBitmap(bmFinger, width);
		Bitmap sourceImg = bmFinger1.copy(Bitmap.Config.ARGB_8888, true);
		int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];

		sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0,
				sourceImg.getWidth(), sourceImg.getHeight());// 获得图片的ARGB值

		// number = number * 255 / 100;

		for (int i = 0; i < argb.length; i++) {
			if (((argb[i] & 0x000000FF) > 0x00000096)
					|| (argb[i] & 0x0000FF00) > 0x00009600) {
				argb[i] = (0 << 24) | (argb[i] & 0x00FF0000);
			} else {
				// argb[i] = (0xff << 24) | (argb[i] & 0x00FFFFFF);//原图红
				argb[i] = (0xff << 24) | (argb[i] & 0x00FF0000);// 这里改为了纯红
			}

		}

		sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg

				.getHeight(), Config.ARGB_8888);

		return sourceImg;
	}
}
